<template>
  <el-dialog
    v-model="dialogVisible"
    title="设置映射列"
    width="500px"
    @close="resetForm"
  >
    <el-form ref="serviceForm" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="映射列" prop="mappingIds">
        <el-select
          ref="userSelectRef"
          v-model="form.mappingIds"
          placeholder="请选择"
          filterable
          multiple
          remote
          :remote-method="onKeywordInput"
          class="w-full"
          clearable
          @visible-change="onUserDropdownVisibleChange"
        >
          <el-option
            v-for="item in list"
            :key="item.id"
            :label="item.originalName"
            :value="item.id"
          />
          <template v-if="userLoading" #footer>
            <div class="text-center text-xs text-gray-500">
              <span>加载中...</span>
            </div>
          </template>
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" :loading="submitLoading" @click="handleConfirm"
        >确定</el-button
      >
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, nextTick, reactive } from "vue";
import { putMappingIds } from "@/api/adminStandardColumnApi";
import { message } from "@/utils/message";

import { useRemotePagedSelect } from "@/composables/useRemotePagedSelect";
import { mapSelectFetcher, type MapItem } from "@/composables/mapSelectFetcher";
import type { ElSelect, FormRules } from "element-plus";

// 用户下拉：远程搜索 + 触底加载
const {
  list,
  loading: userLoading,
  onKeywordInput,
  onDropdownScroll
} = useRemotePagedSelect<MapItem>({
  pageSize: 20,
  autoLoad: true,
  debounceMs: 300,
  fetcher: mapSelectFetcher
});

const userSelectRef = ref<InstanceType<typeof ElSelect> | null>(null);
let userDropdownWrapEl: HTMLElement | null = null;

function onUserDropdownVisibleChange(visible: boolean) {
  if (visible) {
    nextTick(() => {
      const popperEl = userSelectRef.value?.popperRef as
        | HTMLElement
        | undefined;
      // 在该选择器自己的 popper 里找 wrap
      userDropdownWrapEl =
        popperEl?.querySelector(".el-select-dropdown__wrap") ?? null;
      userDropdownWrapEl?.addEventListener("scroll", onDropdownScroll, {
        passive: true
      });
    });
  } else {
    userDropdownWrapEl?.removeEventListener("scroll", onDropdownScroll);
    userDropdownWrapEl = null;
  }
}
const dialogVisible = ref(false);
const emits = defineEmits(["refresh"]);
const id = ref(null);
interface RuleForm {
  mappingIds: string[];
}
const form = ref<RuleForm>({
  mappingIds: []
});
const rules = reactive<FormRules<RuleForm>>({
  mappingIds: [
    {
      required: true,
      message: "请选择映射列",
      trigger: "change",
      type: "array"
    }
  ]
});

const serviceForm = ref(null);
const resetForm = () => {
  serviceForm.value?.resetFields();
  serviceForm.value?.clearValidate();
};
const submitLoading = ref(false);
const handleConfirm = () => {
  serviceForm.value.validate(async valid => {
    try {
      if (valid) {
        submitLoading.value = true;
        await putMappingIds(id.value, form.value);
        message("操作成功", { type: "success" });
        emits("refresh");
        dialogVisible.value = false;
      }
    } finally {
      submitLoading.value = false;
    }
  });
};
const open = (idss, mappingIds) => {
  id.value = idss;
  form.value.mappingIds = mappingIds;
  dialogVisible.value = true;
};
defineExpose({
  open
});
</script>
